# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json

import pymysql as pymysql
from scrapy.exceptions import DropItem


class zbjPipeline(object):
    def __init__(self):
        pass

    insert = '''insert into zbj(text,author,tags)
                            values('{text}','{author}','{tags}')'''

    def process_item(self, item, spider):

        return item

    def open_spider(self, spider):
        # 连接数据库
        self.connect = pymysql.connect(
            host=self.settings.get('MYSQL_HOST'),
            port=self.settings.get('MYSQL_PORT'),
            db=self.settings.get('MYSQL_DBNAME'),
            user=self.settings.get('MYSQL_USER'),
            passwd=self.settings.get('MYSQL_PASSWD'),
            charset='utf8',
            use_unicode=True)

        # 通过cursor执行增删查改
        self.cursor = self.connect.cursor();
        self.connect.autocommit(True)

    def close_spider(self, spider):
        self.cursor.close()
        self.connect.close()


class MyscrapyPipeline(object):
    def __init__(self):
        self.file = open('data.json','w',encoding="utf-8")

    def process_item(self, item, spider):
        if item['title']:
            self.file.write(str(item) + "\n")
            return item
        else:
            raise DropItem("Missing title in %s" % item)
        return item
